package com.example.testnt;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class EchoClientActivity extends AbstractEchoActivity {


    private EditText ip_edit;
    private EditText messageEdit;

    public EchoClientActivity() {
        super(R.layout.activity_echo_client);
    }


    public EchoClientActivity(int layoutID) {
        super(R.layout.activity_echo_client);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ip_edit = findViewById(R.id.ip_edit);
        messageEdit = findViewById(R.id.message_edit);
    }

    @Override
    protected void onStartButtonClicked() {

        String ip = ip_edit.getText().toString();
        Integer port = getPort();
        String message = messageEdit.getText().toString();

        if ((0 != ip.length()) && (port != null) && (0 != message.length())) {

            ClientTask clientTask = new ClientTask(startButton, logView, ip, port, message);
            clientTask.start();
        }
    }

    /**
     * UDP客户端
     *
     * @param ip
     * @param port
     * @param message
     */
    private native void nativeStartUdpClient(String ip, int port, String message);

    /**
     * 发送信息
     *
     * @param ip
     * @param port
     * @param message
     */
    private native void nativeStartTcpClient(String ip, int port, String message);

    private class ClientTask extends AbstractEchoTask {

        private final String ip;
        private final int port;
        private final String message;

        protected ClientTask(Button startButton, TextView logView, String ip, int port, String message) {
            super(startButton, logView);
            this.ip = ip;
            this.port = port;
            this.message = message;
        }

        @Override
        protected void onBackground() {

            logMessage("客户端开始");
            try {
//                nativeStartTcpClient(ip, port, message);
                nativeStartUdpClient(ip, port, message);
            } catch (Throwable e) {

                logMessage(e.getMessage());
            }
            logMessage("客户端终止");
        }
    }
}
